package com.haoyun.common.core.util;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import org.apache.commons.lang3.SerializationException;
import org.apache.commons.lang3.Validate;
import org.springframework.lang.UsesJava8;

import java.io.*;


/**
 * Created by twg on 2018/3/6.
 */
@UsesJava8
public final class SerializationUtils extends org.apache.commons.lang3.SerializationUtils{

    /**
     * 序列化
     * @param obj
     * @return
     */
    public static byte[] serialize(final Serializable obj) {
        final ByteArrayOutputStream os = new ByteArrayOutputStream(512);
        HessianOutput he = new HessianOutput(os);
        try {
            he.writeObject(obj);
        } catch (IOException ex) {
            throw new SerializationException(ex);
        }
        return os.toByteArray();
    }

    /**
     * 反序列化
     * @param objectData
     * @param <T>
     * @return
     */
    public static <T> T deserialize(final byte[] objectData) {
        Validate.isTrue(objectData != null, "The byte[] must not be null");
        return org.apache.commons.lang3.SerializationUtils.deserialize(new ByteArrayInputStream(objectData));
    }

    public static <T> T deserialize(final InputStream inputStream) {
        Validate.isTrue(inputStream != null, "The InputStream must not be null");
        try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
            HessianInput he = new HessianInput(in);
            return (T) he.readObject();
        } catch (IOException ex) {
            throw new SerializationException(ex);
        }
    }
}
